/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2022-12-09 11:19:35
 * @LastEditors: huangtianyang
 * @LastEditTime: 2023-08-31 15:05:56
 * @FilePath: \cxl-admin\src\utils\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { refreshToken } from '@/apis/login/login'
import { storage } from '@/store/sessionStorage'
/**
 * 校验输入的密码，至少8位，包含数字+字母
 * @param password
 */
export const checkPassword = (password: string) => {
    let result = false
    if (password == '' || password == null || password.length < 8) {
        result = false
        return false
    }
    const reg = new RegExp(/^(?![^a-zA-Z]+$)(?!\D+$)/)
    if (reg.test(password)) {
        result = true
    }
    return result
}

/**
 * 验证手机号码
 * @param mobile
 * @returns
 */
export const regMobile = (mobile: string) => {
    return /^1[3456789]\d{9}$/.test(mobile)
}
/**
 * 验证输入的银行卡号
 * @param card
 * @returns
 */
export const regBankAccount = (card: string) => {
    return /^([1-9]{1})(\d{15}|\d{16}|\d{18})$/.test(card)
}

/**
 *
 * @param data      数据源
 * @param key       每一项的ID key
 * @param parentKey 每一项的父级ID key
 * @returns []
 *
 * handleTree(list,'id','parentId')
 */
export function handleTree(data: any[], key: string, parentKey: string) {
    //创建一个空数组
    const result: any[] = []

    //创建一个map数组
    const map = new Map()
    map.clear()

    data.map((item: any) => {
        //以每一项的id值作为键
        map.set(item[key], item)
    })

    data.forEach((item: any) => {
        //从map中取出item对应的父值
        const parent = map.get(item[parentKey])

        //判断其父是否存在
        if (parent) {
            //存在则把 item 添加到 parent.children 中
            if (parent.children) {
                parent.children.push(item)
            } else {
                parent.children = []
                parent.children.push(item)
            }
        } else {
            //不存在 则添加到 result 中
            result.push(item)
        }
    })

    return result
}

//通过秒转换时间
export const timeFilterToSeconds = (seconds: number) => {
    let ss: number | string = parseInt(seconds.toString()) // 秒
    let mm: number | string = 0 // 分
    let hh: number | string = 0 // 小时
    if (ss > 60) {
        mm = Number(parseInt((ss / 60).toString()))
        ss = parseInt((ss % 60).toString())
    }
    if (mm > 60) {
        hh = parseInt((mm / 60).toString())
        mm = parseInt((mm % 60).toString())
    }
    let result = ('00' + parseInt(ss.toString())).slice(-2)
    if (mm > 0) {
        result = ('00' + parseInt(mm.toString())).slice(-2) + '分:' + result + '秒'
    } else {
        result = '00分:' + result + '秒'
    }
    if (hh > 0) {
        result = ('00' + parseInt(hh.toString())).slice(-2) + '时:' + result
    }
    return result
}

//设置倒计时
export class CountDown {
    //定时器
    timer: null | number | undefined | NodeJS.Timer

    //当前时间
    currentTime = 0

    //截至时间
    endTime = 0

    //当前时间距离截至时间
    intervalTime = 0

    //用户登录时间
    userLoginTime = 0

    second = 0

    //second 秒
    constructor(second: number) {
        console.log('second', second)
        this.second = second
        this.currentTime = new Date().getTime()
        //获取登录时间
        this.userLoginTime = Number(sessionStorage.getItem('loginTime'))

        /**
         * 从登录时间开始计算 倒计时 second分钟
         *
         * 1、创建登录时间对象
         * const loginDate = new Date(this.userLoginTime)
         * 2、通过loginDate得到分钟
         * const loginMinute = loginDate.getMinutes()
         * 3、
         * const endMinute = loginMinute + second
         * 4、
         * const e = loginDate.setMinutes(endMinute)
         * 5、再new Date()
         * const endDate = new Date(e)
         * 6、调用
         * this.endTime = endDate.getTime()
         */

        const loginDate = new Date(this.userLoginTime)
        //Date.setMinutes(min, sec, millisec) min必需。表示分钟的整数。
        // this.endTime = new Date(loginDate.setMinutes(loginDate.getMinutes() + Math.round(this.minute))).getTime()
        this.endTime = new Date(loginDate.setSeconds(loginDate.getSeconds() + Math.round(this.second))).getTime()

        console.log(
            second,
            '登录时间',
            this.userLoginTime,
            '当前时间',
            this.currentTime,
            '相差',
            timeFilterToSeconds((this.currentTime - this.userLoginTime) / 1000),
            '截至时间',
            this.endTime
        )
        clearInterval(storage.get('countDownTimer'))
    }
    start(callback = () => {}) {
        this.stop()
        let s = 0
        this.timer = setInterval(() => {
            this.currentTime = new Date().getTime()
            this.intervalTime = this.endTime - this.currentTime // 两个时间戳相隔的毫秒数
            s = parseInt((this.intervalTime / 1000).toString())
            // console.log(this.intervalTime)
            if (s > 0) {
                //console.log('time', timeFilterToSeconds(s))
            } else {
                refreshToken().then(e => {
                    //this.setToken(e.data.data.accessToken)
                    storage.set('loginTime', new Date().getTime().toString())
                    storage.set('token', e.data.data.accessToken)
                    storage.set('refreshToken', e.data.data.refreshToken)
                    storage.set('expire', (e.data.data.expire - 5).toString())
                    new CountDown(this.second).start()
                })
                this.stop(callback)
            }
        }, 1000)

        storage.set('countDownTimer', this.timer.toString())
    }
    stop(callback = () => {}) {
        if (this.timer) {
            clearInterval(this.timer)
            callback()
        }
    }
}

export const CreateXMLHttpRequest = (url: string, fileName: string) => {
    const xhr = new XMLHttpRequest()
    xhr.open('get', url, true)
    xhr.responseType = 'blob'
    xhr.setRequestHeader('Authorization', storage.get('token'))
    xhr.onload = function () {
        if (xhr.status === 200) {
            const blob = new Blob([this.response], { type: 'application/vnd.ms-excel;charset=utf-8' })
            const a = document.createElement('a')
            const u = window.URL.createObjectURL(blob)
            a.href = u
            a.download = fileName + '.xlsx'
            a.click()
            window.URL.revokeObjectURL(url)
        }
    }
    xhr.send()
}
